package com.example.campuslink.commen.tools

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import com.example.campuslink.R
import java.util.Date
import java.util.Random

class TextToImageUtil {
    private
    var canvas: Canvas? = null

    private
    var x: Float = 0f

    private
    var y: Float = 0f

    private
    var bitmap: Bitmap? = null

    private
    var paint: Paint? = null

    private
    var text: String? = null

    private
    val random: Random = Random()

    private
    val emojiList: IntArray = intArrayOf(
        R.drawable.emoji1, R.drawable.emoji2, R.drawable.emoji3, R.drawable.emoji4,
        R.drawable.emoji5, R.drawable.emoji6, R.drawable.emoji7
    )

    private
    var directory: File? = null

    fun createTextImage(
        text1: String,
        width: Int,
        height: Int,
        textSize: Int,
        textColor: Int,
        fontFamily: String?,
        backgoundcolor: Int,
        context: Context,
        emoji: Boolean
    ): Bitmap {
        //创建视图
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        //创建画布
        canvas = Canvas(bitmap!!)
        text = text1
        paint = Paint()
        paint!!.color = textColor
        paint!!.textSize = textSize.toFloat()
        if (fontFamily != null) {
            paint!!.setTypeface(Typeface.create(fontFamily, Typeface.NORMAL))
        }
        if (backgoundcolor != -1) {
            canvas!!.drawColor(backgoundcolor)
        }


        if (emoji) {
            canvas!!.drawColor(Color.WHITE)
            val emojicount = random.nextInt(15 - 0 + 1)
            for (i in 0..<emojicount) {
                val rom = random.nextInt(emojiList.size)

                val resources = context.resources
                val drawable = resources.getDrawable(emojiList[rom])
                //                Toast.makeText(context, "weigh:"+width+"height:"+height, Toast.LENGTH_SHORT).show();
                val temp = drawableToBitmap(drawable, width, height)
                if (temp != null) {
                    val matrix = Matrix()
                    matrix.setRotate(random.nextInt().toFloat())
                    canvas!!.drawBitmap(temp, matrix, null)
                }
            }
        }
        // 获取文字的宽度和高度，以便进行合适的布局
        val fontMetrics = paint!!.fontMetrics
        val textWidth = paint!!.measureText(text1)
        val textHeight = fontMetrics.bottom - fontMetrics.top

        // 计算文字的起始坐标，使其在图片中居中显示（这里只是一种简单的居中方式示例）
        x = (width - textWidth) / 2
        y = (height + textHeight) / 2 - fontMetrics.bottom

        canvas!!.drawText(text1, x, y, paint!!)

        return bitmap ?: Bitmap.createBitmap(0, 0, Bitmap.Config.ARGB_8888)
    }

    fun drawableToBitmap(drawable: Drawable, width: Int, height: Int): Bitmap {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }

        //创建视图
        val bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888)
        //创建画布
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, width, height)
        drawable.draw(canvas)
        //返回视图
        return bitmap
    }

    fun getBitmapPath(): String {
        return directory?.absolutePath ?: ""
    }

    fun saveBitmapToExternalStorage() {
        if (isExternalStorageWritable()) {
            //创建保存路径

            directory = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .toString() + "/" + SimpleDateFormat("yyyyMMddHHmmss").format(
                    Date()
                ) + "wordDraw" + ".png"
            )
            if (directory != null) {
                try {
                    //保存内容
                    val fos = FileOutputStream(directory)
                    bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                    fos.flush()
                    fos.close()
                    canvas?.drawColor(Color.WHITE)
                    canvas?.drawText(text!!, x, y, paint!!)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }


    private fun isExternalStorageWritable(): Boolean {
        val state = Environment.getExternalStorageState()
        return Environment.MEDIA_MOUNTED == state
    }
}